*Generate Macrodata
version 12

tempfile td1 td2
*WDI data
use "./orgdata/wdidata.dta",clear
drop  CountryName
rename cunemploy Cunemploy
lab var Cunemploy "Unemployment (%,2002)"
rename cimmiwdi Cforeign 
lab var Cforeign "Foreign born (%,2000)"
rename cgdpcap Cgdpcap
lab var Cgdpcap  "GDP/capita 2002"
notes Cunemploy: source WDI
notes Cgdpcap: PPP, constant 20005$, source WDI
lab var id "Country id"

save `td1',replace

*Manifesto data
use "./orgdata/MPDataset_full.dta" ,clear

include "./scripts/lookupid.do"
rename id_new id

gen eyear = year(edate)
sort country eyear
keep if eyear >1989
keep if eyear <2003
gen rparty = 0
replace rparty = 1 if inlist(party, 42420, 21914, 82710, 13951, 13720, 31720, 86620, 72530, 72624, 32720, 32710, 22720, 12951, 97710, 11951, 43810, 43711, 43710, 43951)

keep id per607 per608 per601 per602 country edate eyear party rparty
gen multi = per607+per608
*gen MapmultiNP = per608 - per607
gen MapmultiN = per608
gen MapmultiP = per607
bys id eyear:  egen mdev= sd(multi)
bys id eyear:  egen Mapmulti= mean(multi)
*gen MapmultiW = Mapmulti*(100-mdev)
*gen test = Mapmulti /mdev
*gen MapmultiW2 = Mapmulti*test

bys id: egen tempmax = max(eyear)
gen MapmultiLAST = per607+per608 if eyear==tempmax
gen MapmultiNLAST = per608 if eyear==tempmax
*gen MapmultiNPLAST = per608 - per607 if eyear==tempmax
*gen MapmultiW2LAST = Mapmulti*test if eyear==tempmax
*replace MapmultiW2LAST = 0 if eyear==tempmax & id==348
*drop test
*bys id eyear: gen Mnumparty = _N



collapse M* , by(id eyear)
collapse M* ,by(id)
gen MapmultiR = MapmultiN/MapmultiP
lab var id "Country id"
lab var MapmultiN "PolPartyFocus, Negative"
lab var MapmultiP "PolPartyFocus, Positive"
lab var Mapmulti "PolPartyFocus, Total"
lab var MapmultiLAST "PolPartyFocus, Total, Last elec."
lab var MapmultiNLAST "PolPartyFocus, Negative, Last elec."
lab var MapmultiR "PolPartyFocus, Ratio"

drop if id==.

merge 1:1 id using "./orgdata/landid.dta"
keep if _merge ==3
drop _merge
save `td2'

use `td1'
merge 1:1 id using `td2'
drop _merge
compress

save "./gendata/macrodata",replace
tempfile td1 td2
exit
